package data;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutionException;

import android.app.Activity;

/**
 * Creates a task that gets an account from the database
 * 
 * @author Kelsey
 */
public class GetAccount extends DBTask<Void, Void, Account> {

	/** the name of the account to get */
	private String accountName = null;

	/**
	 * construct task to get account
	 * 
	 * @param activity
	 *            the current activity
	 * @param accountName
	 *            the name of the account to get
	 * @throws DBInterfaceError
	 */
	public GetAccount(Activity activity, String accountName)
			throws DBInterfaceError {
		super(activity);

		this.accountName = accountName;
	}

	/**
	 * gets the account from a database
	 * 
	 * @return account
	 * @throws DBInterfaceError
	 */
	@Override
	public Account getResult() throws DBInterfaceError {
		execute();
		Account account = null;
		try {
			account = get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		return account;
	}

	/**
	 * Searchs for and returns an account from a database
	 * 
	 * @param args
	 *            - this is ignored, but neccessary because of the abstract
	 *            class
	 * @return account from database
	 */
	@Override
	protected Account doInBackground(Void... arg0) {
		PreparedStatement getItemsQuery;
		Account account = null;
		try {
			getItemsQuery = conn
					.prepareStatement("SELECT * FROM account WHERE accountName=?");
			getItemsQuery.setString(1, accountName);
			ResultSet set = getItemsQuery.executeQuery();
			account = new Account();
			while (set.next()) {
				account.setAccountName(set.getString("accountName"));
				account.setEmail(set.getString("email"));
				account.setPassword(set.getString("password"));
				account.setRealName(set.getString("realName"));
				account.setPhoneNumber(set.getString("phoneNumber"));
				account.setLoginTimes(set.getInt("loginTimes"));
				account.setIsLocked(set.getBoolean("locked"));
				account.setIsAdmin(set.getBoolean("isAdmin"));
			}
		} catch (Exception e) {
			System.err.println(e);
		}

		return account;
	}

}
